package online.shenme.day15;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
//UDP数据接收
public class UDPReceive {
    public static void main(String[] args) throws IOException, InterruptedException {
        InetAddress address = InetAddress.getByName("127.0.0.1");
        System.out.println(address.getHostAddress());
        System.out.println(address);

        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 5, 10, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(10));

        pool.submit(() -> {
            byte[] dates = new byte[1024];
            try (DatagramSocket service = new DatagramSocket(10000)) {
                DatagramPacket packet = new DatagramPacket(dates, dates.length);
                service.receive(packet);
                System.out.println(new String(dates, 0, packet.getLength()));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                pool.shutdown();
            }
        });
    }
}

//UDP数据包发送
class UDPSend {
    public static void main(String[] args) throws IOException {
        byte[] bytes = "Hello".getBytes(StandardCharsets.UTF_8);
        DatagramSocket send = new DatagramSocket();
        send.send(new DatagramPacket(bytes, bytes.length, InetAddress.getByName("Johnzz"), 10000));
    }
}
